<?php
include '../../../wp-blog-header.php';
$url = 'http://www.foodome.in/deal_xml.php';
$brand_id = '332';

function download_page($path){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$path);
        curl_setopt($ch, CURLOPT_FAILONERROR,1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 15);
        $retValue = curl_exec($ch);                      
        curl_close($ch);
        return $retValue;
}

$curl_output = download_page($url);

$deals = xml2array($curl_output);

$deals = $deals['dealinfo']['deals'];

/*
echo '<pre>';
print_r($deals);
echo '</pre>';
exit();
*/

foreach($deals as $key=>$value)
{
  date_default_timezone_set('Asia/Kolkata');
  if(strtotime($value['expires_on']) >= strtotime(date('Y-m-d')))
  {
    $columns_deal['name'] = pods_sanitize($value['deal_name']);
    $columns_deal['camp_link'] = sanitize_title($columns_deal['name']);
    $ext_img_url =$value['image_path'];
     
    $deal = new Pod('deal');
    $where = 't.camp_link = "'.$columns_deal['camp_link'].'" OR (t.ext_image_url = "'.$ext_img_url.'" AND t.daily = "1")';
    $deal->findRecords('id DESC', 1,$where);
    $dealsFound = $deal->getTotalRows();
    if($dealsFound == 0)
    {
      //echo $i.' : '.$value['title']."<br />";
      //$i++;
      if($value['city'] == 'Delhi/NCR')
      {
        $value['city'] = 'Delhi';
      }
      
      $city_name = $value['city'];
      $city = new Pod('city');
    	$city->findRecords("name ASC",1,"t.name = '$city_name'");
    	while($city->fetchRecord())
    	{
      	$city_id  = $city->get_field('id');
    	}
    
      $columns_deal['city'] = $city_id;
      //$columns_deal['short'] = $value['description'];
      
      $shortened_url = make_bitly_url($value['url']);
      if(empty($shortened_url))
      {
        $shortened_url = make_goog_url($value['url']);
      }
      $columns_deal['extlink'] = $shortened_url;
      
      $columns_deal['camp_end'] = date('Y-m-d 23:59:00',strtotime('+2 day',strtotime(date("Y-m-d 12:00:00"))));
      $columns_deal['camp_start'] = date('Y-m-d H:i:s');
      $columns_deal['brand'] = $brand_id;
      $columns_deal['daily'] = '1';
      $columns_deal['oriprice'] = floor($value['value']);
      $columns_deal['disper'] = floor($value['discount']);
      $columns_deal['disprice'] = floor($value['you_pay']);
      $columns_deal['ext_image_url'] = $value['image_path'];
      $columns_deal['camp_cat'] = '24';//Restaurants & Clubs
    
      $api = new PodAPI();
      $params = array('datatype' => 'deal', 'columns' => $columns_deal);
      
      
      //echo '<pre>';
      //print_r($params);
      //echo '</pre>';
      //exit();
      
      
      $api->save_pod_item($params);
    }
  }
}